
#include "touch_gt9x.h"
#include "string.h"

static void gt9x_soft_reset(touch_gt9x_t *ic)
{
    gt9x_reg_ctrl_t reg_ctrl = {.value=0};
    reg_ctrl.reset = 1;
    ic->bus->write_reg(ic->bus_handle, ic->addr, GT9x_CTRL, &reg_ctrl.value, 1);
    hal_delay_ms(100);
}

void gt9x_init(touch_gt9x_t *ic, uint8_t address, 
                uint8_t *cfg, uint8_t cfg_len,
                touch_data_t *p, uint8_t p_num )
{
    ic->base.point = p;
    ic->base.point_num = p_num;
    ic->addr = address;
    ic->bus->reset(ic->bus_handle, 20, 100);
    gt9x_soft_reset(ic);
    if(cfg!=0 && cfg_len>0)
        ic->bus->write_reg(ic->bus_handle, ic->addr, GT9x_CFGS, cfg, cfg_len);
    ic->bus->read_reg(ic->bus_handle, ic->addr, GT9x_PID, (uint8_t *)&ic->id, 4);
}

void gt9x_read_points(touch_gt9x_t *ic)
{
    uint8_t i, num = 0;
    gt9x_reg_status_t reg_status;
    gt9x_reg_coordinate_t reg_coord;
    
    ic->bus->read_reg(ic->bus_handle, ic->addr, GT9x_GSTID, &reg_status.value, 1);
    
    if(reg_status.ready) {
        ic->base.status = reg_status.valid_points;
        memset(ic->base.point, 0, sizeof(touch_data_t)*ic->base.point_num);
        if(reg_status.valid_points) {
            num = MIN(reg_status.valid_points, ic->base.point_num);
            for(i=0;i!=num;i++) {
                ic->bus->read_reg(ic->bus_handle, ic->addr, GT9x_TP1+i*8, (uint8_t *)&reg_coord, 8);
                ic->base.point[i].x = reg_coord.x;
                ic->base.point[i].y = reg_coord.y;
                ic->base.point[i].track_id = reg_coord.id;
                ic->base.point[i].width = reg_coord.size;
                ic->base.point[i].event = kTouchEventPressed;
            }
        }
        reg_status.value = 0; //clear status flag
        ic->bus->write_reg(ic->bus_handle, ic->addr, GT9x_GSTID, &reg_status.value, 1);
    }
}
